var app = getApp()
/**
 * 列表初始化
 */
var listObjs = {}
function init(list_id, options) {
  var pages = getCurrentPages();
  var list_id = list_id || '';
  if (list_id == '') {
    list_id = pages[pages.length - 1].__wxWebviewId__;
  }

  //初始化全局变量--保存列表对象
  var listObj = {
    current_page: 1,
    per_page: options.pageNum || 10,
    url: options.url,
    data: options.data || {},
  }
  listObjs[list_id] = listObj;
}

function load(__wxWebviewId__, succCb, failCb) {
  var listObj = listObjs[__wxWebviewId__];
  if (listObj) {
    var data = listObj.data;
    data.page = listObj.current_page;
    data.per_page = listObj.per_page;
    app.Ajax({
      url: listObj.url,
      data: data,
      success: (res) => {
        if (res.list.length > 0) {
          listObj.current_page = listObj.current_page + 1;
        }
        typeof succCb == 'function' && succCb(res.list);
      },
      fail: (err, code) => {
        typeof failCb == 'function' && failCb(err, code);
      }
    })
  } else {
    typeof failCb == 'function' && failCb('list id is wrong!');
  }
}

function reload(__wxWebviewId__, succCb, failCb) {
  var listObj = listObjs[__wxWebviewId__];
  if (listObj) {
    listObj.current_page = 1;
    var data = listObj.data;
    data.current_page = listObj.current_page;
    data.per_page = listObj.per_page;
    app.Ajax({
      url: listObj.url,
      data: data,
      success: (res) => {
        res = res.data;
        if (res.state.code == 0) {
          listObj.current_page = listObj.current_page + 1;
          typeof succCb == 'function' && succCb(res.data);
        } else {
          typeof failCb == 'function' && failCb();
        }
      },
      fail: (err, code) => {
        typeof failCb == 'function' && failCb(err, code);
      }
    })
  }
}

module.exports = {
  init: init,
  load: load,
  reload: reload,
}